// Generate Master Monthly File
// Load Raw Monthly Data
use "../src/stock_monthly.dta", clear

// Defining Vintage Variables
merge m:1 code using ../src/0th_shsz 
drop if _merge ==2 
gen vintage0 = 0
replace vintage0 = 1 if _m == 3
drop _merge

merge m:1 code using ../src/1st_shsz 
drop if _merge ==2 
gen vintage1 = 0
replace vintage1 = 1 if _m == 3 & vintage0 == 0
drop _merge 

merge m:1 code using ../src/2nd_shsz 
drop if _merge ==2 
gen vintage2 = 0
replace vintage2 = 1 if _m == 3 & vintage1 == 0 & vintage0 == 0   
drop _merge 

merge m:1 code using ../src/3rd_shsz 
drop if _merge ==2 
gen vintage3 = 0
replace vintage3 = 1 if _m == 3 & vintage2 == 0 & vintage1 == 0  & vintage0 == 0   
drop _merge 

merge m:1 code using ../src/4th_shsz 
drop if _merge ==2 
gen vintage4 = 0
replace vintage4 = 1 if _m == 3 & vintage3 == 0 & vintage2 == 0 & vintage1 == 0  & vintage0 == 0  
drop _merge 

// Defining Vintage On
gen vintage4_on = 0
replace vintage4_on = 1 if date2>=ym(2014,9)

gen vintage3_on = 0
replace vintage3_on = 1 if date2>=ym(2013,9)

gen vintage2_on = 0
replace vintage2_on = 1 if date2>=ym(2013,1)

gen vintage1_on = 0
replace vintage1_on = 1 if date2>=ym(2011,12)

gen vintage0_on = 0
replace vintage0_on = 1 if date2>=ym(2010,3) 

// drop the stocks listed on growth enterprise board (GEB)
gen n = int(code/100000)
drop if n==3

// drop the stocks with negative or missing equity value in the previous year
drop if equity_1<0
drop if equity_1==.

// drop the six stocks that were added to the marginable list off-cycle
// between the times of pilots A and B
// all were added in July, 2010
drop if code == 728     /* added in 2010.7.1  */
drop if code == 601288  /* added in 2010.7.29 */
drop if code == 601618  /* added in 2010.7.1  */
drop if code == 601699  /* added in 2010.7.1  */
drop if code == 601788  /* added in 2010.7.1  */
drop if code == 601998  /* added in 2010.7.1  */


tset code date2 
gen float_cap_f1 = f1.float_cap


gen ln_float_f1    = ln(float_cap_f1 + sqrt(1+float_cap_f1^2))
gen ln_margin_hold = ln(margin_hold  + sqrt(1+margin_hold^2))

drop if ln_float_f1==.
drop if ln_margin_hold==.

gen vintage=0 if vintage0==1
replace vintage=1 if vintage1==1
replace vintage=2 if vintage2==1
replace vintage=3 if vintage3==1
replace vintage=4 if vintage4==1

save ../dta/stock_monthly_vintage.dta, replace
